const BASE_URL_TEST = import.meta.env.VITE_BASE_PATH

import axios, {
  type AxiosError,
  type AxiosRequestConfig,
  type InternalAxiosRequestConfig
} from 'axios'

import { type UserType } from '../types/type53'

interface AxiosRequestConfigEx extends AxiosRequestConfig {
  donNotShowLoading?: boolean
}

// 创建一个自定义 axios 实例
const axiosInstance = axios.create({
  // 基本的url
  baseURL: BASE_URL_TEST
  // 超时的时间
  // timeout: 10000,
  // headers: { 'X-Custom-Header': 'foobar' } // 请求头
})

// http request 拦截器
// 请求拦截
axiosInstance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  // 使用 set方法来设置 headers
  config.headers.set('Content-Type', 'application/json')
  config.headers.set(
    'Authorization',
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySW5mbyI6eyJ1c2VySWQiOjEwMjA3LCJ1c2VybmFtZSI6ImxpYW93ZW5qaW5nIiwibmlja25hbWUiOiLlu5bmlofpnZkiLCJkZXB0SWQiOjEsInJvbGVzIjoiQURNSU4ifSwiaXNzIjoiZHlzNjIzMCIsImV4cCI6MTczMTM1MTMyOSwibmJmIjoxNzMxMzE1MzM5LCJpYXQiOjE3MzEzMTUzMjl9.Q8nfBskPZ2DjB04ozQY8HHl9FBqyGtyo10qBnqHP5YI'
  )

  return config
}),
  (error: AxiosError) => {
    // 请求报错
    Promise.reject(error)
  }

// 响应拦截
axiosInstance.interceptors.response.use(
  (response) => {
    // 响应成功时做一些处理
    console.log('响应拦截器：', response)
    return response
  },
  (error) => {
    //
    if (error.response.status === 401) {
      // 如果是 401 错误，可能是未授权，跳转到登录页面
      window.location.href = './login'
    } else if (error.response.status === 500) {
      // 服务器错误
      console.log('服务器错误')
    }
    return Promise.reject(error)
  }
)

// 服务请求 axios请求封装service
export const service = <T = any>(config: AxiosRequestConfigEx) => {
  return axiosInstance.request<UserType>(config).then((response) => {
    return response.data
  })
}

// 获取用户分页列表
export const getUsersPage = (params: any) => {
  return service<UserType>({
    method: 'get',
    url: '/users/page',
    params
  })
}

// post 添加用户
export const PostUsers = (data: any) => {
  return service<UserType>({
    method: 'post',
    url: '/users',
    data
  })
}

// put 通过用户的id修改用户信息
export const PutUsersByUserId = (userId: number, data: UserType) => {
  return service<UserType>({
    method: 'put',
    url: `/users/${userId}`,
    data
  })
}

// delete 删除用户
export const DeleteUsersByIds = (ids: string) => {
  return service<UserType>({
    method: 'delete',
    url: `/users/${ids}`
  })
}

/**
 * 登录
 * @param data 
 * @returns 
 */
export const apiLogin = (data: UserType) => {

  return service<string>({
    method: 'post',
    url: '/auth/login',
    data,
  })
}


/**
 * 登录
 * @param data 
 * @returns 
 */
export const apiUsersMe = () => {

  return service<UserType>({
    method: 'get',
    url: '/users/me'
  })
}
